<template>
  <div class="choose-organization-container">
    <a-popover
      trigger="click"
      overlayClassName="choose-organization-popover"
      :destroyTooltipOnHide="true"
      v-model="visible"
      @visibleChange="visibleChange($event)"
    >
      <div class="popover-target-container">
        <div class="name">
          {{ currentTenant.orgName || "" }}
        </div>
        <a-icon type="down" :class="visible && 'rotate'" />
      </div>
      <!-- popover内容区域 -->
      <div slot="content" class="popover-drow-container">
        <div class="popover-drow-header">
          <div class="tenant-name">
            <a-input-search
              placeholder="请输入关键字"
              style="width: 100%"
              @search="onSearch($event)"
              v-model="keyWord"
              allow-clear
            />
          </div>
        </div>
        <div class="popover-drow-body">
          <!-- 组织结构树 -->
          <div class="carousel-item-container">
            <a-tree
              :tree-data="orgSource"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              show-icon
              blockNode
              :replaceFields="{
                children: 'children',
                title: 'orgName',
                key: 'orgCode',
              }"
              @expand="onExpand"
              @select="selectOrganization"
            >
              <icon-fonts
                slot="group"
                icon="icon-shuxingxitongcanshu"
                class="tree_line"
              ></icon-fonts>
              <template
                slot="custom"
                slot-scope="{ children, expanded, selected }"
              >
                <!-- expanded 展开  children 是否包含子节点 -->
                <a-icon
                  :type="expanded ? 'folder-open' : 'folder'"
                  v-if="children && children.length > 0"
                />
                <icon-fonts
                  v-else
                  class="project_space"
                  icon="icon-xiangmu2"
                ></icon-fonts>
              </template>
            </a-tree>
          </div>
        </div>
      </div>
    </a-popover>
  </div>
</template>

<script>
import cloneDeep from "lodash.clonedeep";
import { mapGetters } from "vuex";
import { addAttributeByKey, flatTreeData, _getUUID } from "@/utils/util.js";
import { notification } from "ant-design-vue";
import { axios } from "@/utils/request";
export default {
  name: "ChooseOrganization",
  data() {
    return {
      //是否可见
      visible: false,
      //组织结构数据
      orgSource: [],
      //当前选择的租户
      currentTenant: {},
      expandedKeys: [],
      selectedKeys: [],
      autoExpandParent: true,
      currenData: {},
      //关键字
      keyWord: "",
      cloneTreeData: [],
    };
  },
  computed: {
    ...mapGetters([
      "tenantData",
      "currentProjectCode",
      "systemName",
      "configData",
    ]),
    systemName() {
      let index = this.configData.findIndex(
        (item) => item.code === "systemName"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "低代码开发平台";
      }
    },
  },
  watch: {
    //当前选择的租户
    currentProjectCode: {
      handler(val) {
        let { tenantData } = this;
        let flatData = flatTreeData(tenantData, "children");
        if (val) {
          this.currentTenant = flatData.find((v) => v.orgCode == val);
        } else {
          this.currentTenant = tenantData?.[0] ?? {};
          this.saveData(this.currentTenant);
        }
        this.expandedKeys = flatData.map((v) => v.orgCode);
        this.selectedKeys = [this.currentTenant?.orgCode];
      },
      immediate: true,
      deep: true,
    },
    //租户列表数据
    tenantData: {
      handler(val) {
        this.cloneTreeData = cloneDeep(val ?? []);
        //格式化树形数据
        let dealData = addAttributeByKey(
          null,
          "scopedSlots",
          { icon: "custom" },
          val,
          "children"
        );
        //处理顶层节点
        if (dealData.length == 1) {
          dealData[0].scopedSlots = { icon: "group" };
        }
        this.orgSource = dealData;
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    // //页面初始化判断是否已缓存项目code
    // let { currentProjectCode, currentTenant } = this;
    // if (!currentProjectCode) {
    //   this.saveData(currentTenant);
    // }
  },
  methods: {
    getLargeScreenButton() {
      axios
        .post(
          `/mdata/transformMdata/judgeDPQX`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.$emit("onRefresh", data);
        })
        .catch((_) => {});
    },

    saveData(ev) {
      localStorage.setItem("CURRENT_PROJECT", JSON.stringify(ev));
      localStorage.setItem("CURRENT_PROJECT_CODE", ev.orgCode);
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT: ev,
      });
      this.$store.dispatch("setStoreState", {
        CURRENT_PROJECT_CODE: ev.orgCode,
      });
    },

    //选择组织结构
    selectOrganization(_, { selected, node }) {
      let { dataRef } = node;
      this.visible = false;
      this.selectedKeys = [dataRef.orgCode];
      this.$store.state.permission.addRouters = [];
      this.$store.state.permission.routers = [];
      this.$store.state.permission.menuData = [];
      this.$store.state.menuData = [];
      this.$store.state.roles = [{ permissions: [] }];
      //
      this.saveData(dataRef);
      this.getLargeScreenButton();
      this.refreshPermission();
    },

    isEmptyObject(obj) {
      return Object.keys(obj).length === 0;
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //刷新权限/菜单数据
    async refreshPermission() {
      await this.$store.dispatch("getPermissionIdentifyingByRoleId");
      await this.$store
        .dispatch("getUserInForAndButtonPermissions")
        .then(async (res) => {
          const roles = res && res.role;
          //菜单信息
          let menuSource = await this.$store.dispatch("GenerateRoutes", {
            roles,
          });

          //首页信息
          let portalSource = JSON.parse(
            localStorage.getItem("PORTAL_ROUTERS_DATA" ?? "[]")
          );

          //默认获取一级节点菜单
          let flatMenu = flatTreeData(menuSource, "children");
          let firstMenu = flatMenu.find(
            (v) => !v.children || v.children.length == 0
          );

          //没有首页，有菜单
          if (portalSource.length == 0 && menuSource.length != 1) {
            this.$router.push({
              path: firstMenu.fullPath,
            });
          }
          //没有首页，没有菜单
          else if (portalSource.length == 0 && menuSource.length == 1) {
            this.$router.push({
              path: `/whitePage/index`,
            });
          }
          //有首页，有菜单
          else {
            this.$router.push({
              path: "/system/portal/index",
            });
          }
          setTimeout(() => {
            //关闭tabs
            this.$store.dispatch("setStoreState", {
              ACTIVE_MENU: _getUUID(),
            });
            this.$emit("change", firstMenu);
          });
        })
        .catch((res) => {
          //2024-08-08 放出提示消息
          notification.error({
            message: "系统提示",
            description: res.message,
            duration: 2,
          });
          setTimeout(() => {
            this.$store.dispatch("Logout").then(() => {
              window.location.reload();
            });
          }, 200);
        });
    },

    onSearch() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.orgSource = this.filterTree(cloneData, "children", (node) =>
        node.orgName.includes(keyWord)
      );
    },
    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },

    //监听显示&隐藏
    visibleChange(visible) {
      //   if (visible) {
      //     let { organization } = this.$store.getters;
      //     this.organizationType = organization.proCode ? 1 : 0;
      //   }
    },
  },
};
</script>

<style lang="less" scoped>
.choose-organization-container {
  width: 360px;
  height: 100%;
  position: relative;
  cursor: pointer;
  .popover-target-container {
    width: 100%;
    height: 100%;
    padding: 0 42px 0 0;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
    overflow: hidden;
    position: relative;
    .name {
      width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      margin-right: 12px;
      text-align: left;
    }
    .anticon {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      font-size: 12px;
      transition: 0.2s;
      &.rotate {
        transform: rotate(-180deg);
        margin-top: -7px;
      }
    }
  }
}
</style>
<style lang="less" scoped>
.choose-organization-popover {
  .ant-popover-inner-content {
    padding: 0;
  }
  .popover-drow-container {
    width: 400px;
    height: 392px;
    display: flex;
    flex-direction: column;
    .popover-drow-header {
      height: 58px;
      border-bottom: 1px solid #e8e8e8;
      display: flex;
      align-items: center;
      flex-shrink: 0;
      .tenant-name {
        flex: 1;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        padding: 0 8px;
        font-size: 16px;
      }
    }
    .popover-drow-body {
      flex: 1;
      padding: 10px 0;
      overflow: hidden;
      .carousel-item-container {
        height: 100%;
        overflow: auto;
        .ant-tree {
          .ant-tree-node-content-wrapper {
            overflow: hidden;
          }
          .ant-tree-title {
            font-size: 15px;
            width: calc(100% - 10px);
            display: inline-block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            padding: 0 10px;
            box-sizing: border-box;
          }
          .tree_line {
            margin-right: 4px;
            &::before {
              font-size: 18px !important;
            }
          }
          .project_space {
            margin-right: 4px;
            &::before {
              font-size: 18px !important;
            }
          }
        }
      }
    }
  }
}
</style>
